<?php
if(!defined('IN_DISCUZ') || !defined('IN_ADMINCP')) {
    exit('Access Denied');
}
$table_er_kami_apibuy_configapi = C::t('#erling_kami_apibuy#er_kami_apibuy_configapi');

if($_GET['action_kami_apibuy']){//处理增删改
    if($_GET['formhash']!= FORMHASH){
        exit('error');
    }
    if($_GET['action_kami_apibuy'] == 'delete'){
        $table_er_kami_apibuy_configapi->delete($_GET['action_kami_configapi_id']);
    }elseif($_GET['action_kami_apibuy'] == 'edit'){
        // 如果url最后一个字符是/，则删除
        $_POST['url'] = preg_replace('#/+$#', '', $_POST['url']);
        $data = array(
            'name' => $_POST['name'],
            'url' => $_POST['url'],
            'private_key' => $_POST['private_key'],
            'desc' => $_POST['desc'],
            'status' => intval($_POST['status']),
            'sort' => intval($_POST['sort']),
            'update_time' => TIMESTAMP
        );
        $table_er_kami_apibuy_configapi->update($_GET['action_kami_configapi_id'], $data);
    }elseif($_GET['action_kami_apibuy'] == 'add'){
        $_POST['url'] = preg_replace('#/+$#', '', $_POST['url']);
        $data = array(
            'name' => $_POST['name'],
            'url' => $_POST['url'],
            'private_key' => $_POST['private_key'],
            'desc' => $_POST['desc'],
            'status' => intval($_POST['status']),
            'sort' => intval($_POST['sort']),
            'create_time' => TIMESTAMP,
            'update_time' => TIMESTAMP
        );
        $table_er_kami_apibuy_configapi->insert($data);
    }
    // 刷新
    $url_page = ADMINSCRIPT.'?action=plugins&operation=config&do='.$pluginid.'&identifier=erling_kami_apibuy&pmod=admin_kami_apibuy_configapi';
    header('Location: '.$url_page);
    exit;
}

$url_page = ADMINSCRIPT.'?action=plugins&operation=config&do='.$pluginid.'&identifier=erling_kami_apibuy&pmod=admin_kami_apibuy_configapi';

// 获取当前列表
$page = max(1, intval($page));
$pagesize = max($_GET['pagesize']??20, intval($pagesize));
$start = ($page - 1) * $pagesize;

$query = [];
if (!empty($_GET['name'])) {
    $query['name'] = $_GET['name'];
    $url_page.= '&name='. $_GET['name'];
}
if (!empty($_GET['url'])) {
    $query['url'] = $_GET['url'];
    $url_page.= '&url='. $_GET['url'];
}
if (!empty($_GET['status'])) {
    $query['status'] = $_GET['status'];
    $url_page.= '&status='. $_GET['status'];
}
$result = $table_er_kami_apibuy_configapi->fetch_all($page, $pagesize, $query);

$kami_list = $result['data'];
$total = $result['total'];

if(!empty($_GET['pagesize'])){
    $url_page .= '&pagesize='.intval($_GET['pagesize']);
}
$multipage = multi($total, $pagesize, $page, $url_page);

include template('erling_kami_apibuy:admin_kami_apibuy_configapi');